<template>
    <div class="login-container">
        <div class="title">Login</div>
        <a-form
            :model="formState"
            ref="formRef"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 16 }"
            autocomplete="off"
            class="login-form"
            >
            <a-form-item
                label="登录名"
                name="name"
                :rules="[{ required: true, message: 'Please input your name!' }]"
            >
                <a-input v-model:value="formState.name" />
            </a-form-item>
            <a-form-item
                label="密码"
                name="password"
                :rules="[{ required: true, message: 'Please input your password!' }]"
            >
                <a-input v-model:value="formState.password" v-focus2 />
            </a-form-item>
            
        
            <a-form-item name="remember" :wrapper-col="{ offset: 4, span: 16 }">
                <a-checkbox v-model:checked="formState.remember">Remember me</a-checkbox>
            </a-form-item>
        
            <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
                <a-button type="primary" html-type="submit" @click="handleLogin">Submit</a-button>
            </a-form-item>
        </a-form>
    </div>
</template>
<script lang="ts" setup>
import { useRouter } from 'vue-router'
import { reactive, ref, toRaw } from 'vue'
import { useUserStore } from '../store/modules/user'

const router = useRouter()
const userStore = useUserStore()
interface FormState {
    name: string;
    password: string;
    remember: boolean;
}
const formRef = ref()
const formState = reactive<FormState>({
  name: '',
  password: '',
  remember: true,
})
const handleLogin = () => {
    formRef.value.validate().then(() => {
        const params = toRaw(formState)
        userStore.login(params).then((res: any) => {
            console.log('res=', res)
            router.replace({name: 'Layout'})
        })
        // router.replace({name: 'Layout'})
    }).catch((error: any) => {
        console.log('error=', error)
    })
}

// 局部注册自定义聚焦指令
const vFocus2 = {
    mounted: (el) => {
        console.log('我是home组件中局部注册的v-focus2指令，声明周期mounted， el=', el)
        el.focus()
    }
}
</script>
<style lang="scss" scoped>
.login-container {
    padding: 50px 0;
}
.title {
    font-size: 24px;
    text-align: center;
    line-height: 40px;;
}
.login-form {
    width: 430px;
    margin: 20px auto;
    padding:30px 10px 10px;
    background: #f5f5f5;
}
</style>